import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../providers/auth_provider.dart';
import '../../utils/validators.dart';
import '../../widgets/custom_text_field.dart';
import '../../widgets/loading_button.dart';

class LoginForm extends StatefulWidget {
  const LoginForm({Key? key}) : super(key: key);

  @override
  State<LoginForm> createState() => _LoginFormState();
}

class _LoginFormState extends State<LoginForm> {
  final _formKey = GlobalKey<FormState>();
  final _usernameController = TextEditingController();
  final _passwordController = TextEditingController();
  bool _rememberMe = false;

  @override
  void dispose() {
    _usernameController.dispose();
    _passwordController.dispose();
    super.dispose();
  }

  Future<void> _handleSubmit() async {
    if (_formKey.currentState!.validate()) {
      final success = await context.read<AuthProvider>().login(
            _usernameController.text,
            _passwordController.text,
            _rememberMe,
          );

      if (success && mounted) {
        // 登录成功后的处理，例如导航到主页
        // Navigator.of(context).pushReplacementNamed('/home');
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    final authProvider = context.watch<AuthProvider>();

    return Form(
      key: _formKey,
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          CustomTextField(
            controller: _usernameController,
            labelText: '用户名',
            validator: Validators.validateUsername,
            prefixIcon: Icons.person,
            textInputAction: TextInputAction.next,
          ),
          const SizedBox(height: 16.0),
          CustomTextField(
            controller: _passwordController,
            labelText: '密码',
            validator: Validators.validatePassword,
            obscureText: true,
            prefixIcon: Icons.lock,
            textInputAction: TextInputAction.done,
            onFieldSubmitted: (_) => _handleSubmit(),
          ),
          const SizedBox(height: 16.0),
          Row(
            children: [
              Checkbox(
                value: _rememberMe,
                onChanged: (value) {
                  setState(() {
                    _rememberMe = value ?? false;
                  });
                },
              ),
              const Text('记住我'),
              if (authProvider.error != null) ...[
                const Spacer(),
                Text(
                  authProvider.error!,
                  style: const TextStyle(color: Colors.red),
                ),
              ],
            ],
          ),
          const SizedBox(height: 24.0),
          LoadingButton(
            text: '登录',
            isLoading: authProvider.isLoading,
            onPressed: _handleSubmit,
          ),
        ],
      ),
    );
  }
}